package com.dc.wifi.main.ui.activity;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.lifecycle.Observer;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.dc.netlib.base.BaseActivity;
import com.dc.wifi.BR;
import com.dc.wifi.R;
import com.dc.wifi.databinding.ActivityTestBinding;
import com.dc.wifi.main.DCApplication;
import com.dc.wifi.main.bean.DeviceDataBean;
import com.dc.wifi.main.model.TestViewModel;
import com.dc.wifi.main.utils.AudioPlayer;
import com.dc.wifi.main.utils.AudioPlayer222;
import com.dc.wifi.main.utils.AudioPlayerUtil;
import com.dc.wifi.main.utils.AudioPlayerUtil222;
import com.dc.wifi.main.utils.LoopingAudioPlayer;
import com.dc.wifi.main.utils.STM32ControlTool;
import com.dc.wifi.main.utils.SoundPlayer;
import com.dc.wifi.main.utils.SoundPlayer222;
import com.dc.wifi.main.utils.Stm32CommunicationTool;

import java.util.Arrays;
import java.util.HashMap;

public class TestActivity extends BaseActivity<TestViewModel, ActivityTestBinding> {
    private AudioPlayer222 audioPlayer222;
    private EditText edit_frequency;
    private AudioPlayerUtil222 audioPlayerUtil222;
    AudioPlayerUtil audioPlayerUtil;
    private AppCompatTextView tv_result;
    private LoopingAudioPlayer loopingAudioPlayer;

    public TestActivity() {
        super(R.layout.activity_test, BR.mTestViewModel);
    }

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
//
//
        stringBuilder.append("信号强度:");
        stringBuilder.append("\n");
        tv_result = findViewById(R.id.tv_result);
        edit_frequency = findViewById(R.id.edit_frequency);
        audioPlayer222 = new AudioPlayer222(this, 1f);
        audioPlayer = new AudioPlayer(this);

        loopingAudioPlayer = new LoopingAudioPlayer(this);


        this.registerReceiver(usbReceiver, new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED));
        findViewById(R.id.btn_scan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (connectDevice) {
                    int startContinuous = stm32ControlTool.performAction("read_phone_number");
                    ToastUtils.showShort(startContinuous);
                } else {
                    xxx();
                }
            }
        });
        findViewById(R.id.btn_phone).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (connectDevice) {
                    int startContinuous = stm32ControlTool.performAction("read_phone_number");
//                    ToastUtils.showShort(startContinuous);
//                    byte[] bytes = stm32ControlTool.readResponse();
//                    ToastUtils.showShort("收到" + Arrays.toString(bytes));
                } else {
                    ToastUtils.showShort("请先连接设备");
                }

            }
        });

        findViewById(R.id.btn_equipmentCode).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (connectDevice) {
                    int startContinuous = stm32ControlTool.performAction("read_device_code");
//                    ToastUtils.showShort(startContinuous);
//                    byte[] bytes = stm32ControlTool.readResponse();
//                    ToastUtils.showShort("收到" + Arrays.toString(bytes));
                } else {
                    ToastUtils.showShort("请先连接设备");
                }

            }
        });
        findViewById(R.id.btn_continuousAcquisitionCommand).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (connectDevice) {
                    stm32ControlTool.performAction("start_continuous");
                } else {
                    ToastUtils.showShort("请先连接设备");
                }
            }
        });
        findViewById(R.id.btn_flagBit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (connectDevice) {
                    stm32ControlTool.performAction("read_permission_flag");
                } else {
                    ToastUtils.showShort("请先连接设备");
                }
            }
        });
        findViewById(R.id.btn_stopIt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (connectDevice) {
                    stm32ControlTool.performAction("stop_capture");
                } else {
                    ToastUtils.showShort("请先连接设备");
                }
            }
        });
        findViewById(R.id.btn_playSound).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                // 初始化SoundPlayer并设置音频资源
//                soundPlayer222 = new SoundPlayer222();
//                soundPlayer222.init(R.raw.qww); // 假设ding是你的音频文件名
//                // 设置播放频率
//                soundPlayer222.setFrequency(5); // 播放频率为5次/秒
//                // 开始播放
//                soundPlayer222.startPlaying();
//                soundPlayer = new SoundPlayer();
//                soundPlayer.init(R.raw.qww);
//
//                // MediaPlayer准备好后调用onPrepared
//                soundPlayer.onPrepared();
//
//                // 设置播放频率
//                soundPlayer.setFrequency(2); // 播放频率为5次/秒
//
//                // 开始播放
//                soundPlayer.play();
//                audioPlayer222.play();
//                audioPlayer.play(); // 开始播放

//                audioPlayerUtil.playAudio(R.raw.zzzz); // 播放音频
//                loopingAudioPlayer.setInterval(2000); // 设置间隔时间为2秒
//
//                loopingAudioPlayer.startWithInterval(); // 开始播放
                audioPlayerUtil = new AudioPlayerUtil(TestActivity.this);
                audioPlayerUtil.play(1000);
            }
        });
        findViewById(R.id.btn_stopSound).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (soundPlayer != null) {
                    soundPlayer.stop();
                }
                if (audioPlayer222 != null) {
                    audioPlayer222.stop();
                }
                if (null != audioPlayer) {
                    audioPlayer.stop();
                }
                if (audioPlayerUtil222 != null) {
                    audioPlayerUtil222.stopAudio();
                }
                if (audioPlayerUtil != null) {
                    audioPlayerUtil.stop();
                }
            }
        });
        findViewById(R.id.btn_modifyFrequency).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                audioPlayer.setFrequency(Float.parseFloat(edit_frequency.getText().toString()));
//                audioPlayer.play();
//                audioPlayer222.setPlayCountPerSecond(Float.parseFloat(edit_frequency.getText().toString()));
                // 可以设置播放间隔，例如1秒后再次播放
//                audioPlayerUtil.setInterval(Integer.parseInt(edit_frequency.getText().toString())); // 1000毫秒
//                loopingAudioPlayer.setInterval(Long.parseLong(edit_frequency.getText().toString())); // 设置间隔时间为2秒
                audioPlayerUtil.play(Long.parseLong(edit_frequency.getText().toString()));
            }
        });
        findViewById(R.id.btn_clearPhoneNumber).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (connectDevice) {
                    stm32ControlTool.performAction("write_phone_number");
                } else {
                    ToastUtils.showShort("请先连接设备");
                }
            }
        });
        findViewById(R.id.btn_clearDeviceCode).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (connectDevice) {
                    stm32ControlTool.performAction("write_device_code");
                } else {
                    ToastUtils.showShort("请先连接设备");
                }
            }
        });
        findViewById(R.id.btn_writeDeviceCode).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (TextUtils.isEmpty(edit_deviceCode.getText())) {
                    ToastUtils.showShort("请输入设备码");
                    return;
                }
                if (!connectDevice) {
                    ToastUtils.showShort("请先连接设备");
                }
                byte[] bytes = {(byte) 0x33, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02};

                String phoneNumber = edit_deviceCode.getText().toString();
                for (int i = 0; i < phoneNumber.length(); i++) {
                    String digit = String.valueOf(phoneNumber.charAt(i));
                    byte x= Byte.parseByte(digit,16);
                    bytes[i+1]=x;
                    LogUtils.d("lufei", digit,x);
                }
                stm32ControlTool.performAction2("write_device_code_2", bytes);
                LogUtils.d("lufeixxx", bytes);
            }
        });
        edit_deviceCode = findViewById(R.id.edit_deviceCode);
        editPleaseEnterYourPhoneNumber = findViewById(R.id.edit_pleaseEnterYourPhoneNumber);
        findViewById(R.id.writePhoneNumber).setOnClickListener(v -> {
            if (TextUtils.isEmpty(editPleaseEnterYourPhoneNumber.getText())) {
                ToastUtils.showShort("请输入手机号");
                return;
            }
            if (!connectDevice) {
                ToastUtils.showShort("请先连接设备");
            }
            byte[] bytes = {(byte) 0x66, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02};

            String phoneNumber = editPleaseEnterYourPhoneNumber.getText().toString();
            for (int i = 0; i < phoneNumber.length(); i++) {
                String digit = String.valueOf(phoneNumber.charAt(i));
                byte x= Byte.parseByte(digit,16);
                bytes[i+1]=x;
                LogUtils.d("lufei", digit,x);
            }
            stm32ControlTool.performAction2("write_phone_number", bytes);
            LogUtils.d("lufeixxx", bytes);
        });
        findViewById(R.id.btn_readPhoneNumber).setOnClickListener(v -> {
            if (connectDevice) {
                int startContinuous = stm32ControlTool.performAction("read_phone_number");
                    ToastUtils.showShort(startContinuous);
                    byte[] bytes = stm32ControlTool.readResponse();
                    ToastUtils.showShort("收到" + Arrays.toString(bytes));
            } else {
                ToastUtils.showShort("请先连接设备");
            }
        });
        findViewById(R.id.clearAll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                byte[] buffer = new byte[1];
                buffer[0]=(byte) 0xee;
                int length = buffer.length;
                int timeout = 5000;
//                int cnt = connection.bulkTransfer(epOut, buffer, length, timeout);// 发送bulk 数据给下位机
                int i = stm32ControlTool.sendCommand3(buffer,5000);
                if (i>=0){
                    ToastUtils.showShort("恢复命令执行成功");
                }else {
                    ToastUtils.showShort("恢复失败");
                }
            }
        });

    }


    private EditText edit_deviceCode, editPleaseEnterYourPhoneNumber;
    private SoundPlayer222 soundPlayer222;
    private SoundPlayer soundPlayer;

    Stm32CommunicationTool stm32CommunicationTool;
    private AudioPlayer audioPlayer;

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void zzzz() {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(DCApplication.getInstance(), notification);
        r.play();
    }

    private void xxx() {
        // 获取UsbManager对象
        UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
// 获取OTG串口设备列表
        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
// 遍历设备列表，找到OTG串口设备
        for (UsbDevice device : deviceList.values()) {
            Log.d("lufeixxx", device.getDeviceName());
            // 定义设备的VID和PID
            int VENDOR_ID = 1137;
            int PRODUCT_ID = 20482;
            // 定义ACTION_USB_PERMISSION
            String ACTION_USB_PERMISSION = getPackageName() + ".USB_PERMISSION";
            // 判断设备是否是OTG串口设备
            if (device.getVendorId() == VENDOR_ID && device.getProductId() == PRODUCT_ID) {
                // 判断设备是否有权限
                if (!usbManager.hasPermission(device)) {
                    // 发送请求获取设备权限
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_IMMUTABLE);
                    usbManager.requestPermission(device, pendingIntent);
                } else {


//                    // 打开OTG串口设备
//                    UsbDeviceConnection connection = usbManager.openDevice(device);
//                    if (connection != null) {
//
//                    }

                    if (!connectDevice) {
                        stm32ControlTool = new STM32ControlTool(usbManager);
                        connectDevice = stm32ControlTool.connectDevice(device);
                        stm32ControlTool.xxxx();
                    }

                    ToastUtils.showShort(connectDevice ? "连接成功" : "连接失败");


                    stm32ControlTool.getDeviceDataBeanMutableLiveData().observe(this, new Observer<DeviceDataBean>() {
                        @Override
                        public void onChanged(DeviceDataBean deviceDataBean) {
                            if (deviceDataBean.type == 0) {
                                int power = deviceDataBean.rawData[0] + (deviceDataBean.rawData[1] << 8);
                                stringBuilder.append(power);
                                stringBuilder.append("\t");

                            }
                            tv_result.setText(stringBuilder);
                        }
                    });

                }
            }
        }
    }

    StringBuilder stringBuilder = new StringBuilder();

    boolean connectDevice = false;
    STM32ControlTool stm32ControlTool;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != stm32ControlTool) {
            stm32ControlTool.disconnectDevice();
        }

        if (null != soundPlayer222) {
            soundPlayer222.release();
        }
        if (soundPlayer != null) {
            soundPlayer.release();
        }
        if (audioPlayer222 != null) {
            audioPlayer222.release();
        }
        if (loopingAudioPlayer != null) {
            loopingAudioPlayer.release(); // 释放资源
        }
    }


    BroadcastReceiver usbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (device != null) {
                    // call your method that cleans up and closes communication with the device
                    ToastUtils.showShort("设备已断开");
                }
            } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                ToastUtils.showShort("设备已连接");
            }
        }
    };
}
